package com.zhang.third.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

/**
 * @title: 使用process实现wordcount
 * @author: zhang
 * @date: 2022/4/1 13:55
 */
public class WordCountWithProcess {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String in, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] array = in.split(" ");
                        for (String word : array) {
                            out.collect(Tuple2.of(
                                    word, 1
                            ));
                        }
                    }
                })
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
                    private ValueState<Tuple2<String, Integer>> cntState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        cntState = getRuntimeContext().getState(
                                new ValueStateDescriptor<Tuple2<String, Integer>>(
                                        "cnt-state", Types.TUPLE(Types.STRING, Types.LONG)
                                )
                        );
                    }

                    @Override
                    public void processElement(Tuple2<String, Integer> value, KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                        if (cntState.value() == null) {
                            cntState.update(value);
                        } else {
                            cntState.update(Tuple2.of(value.f0, value.f1 + cntState.value().f1));
                        }
                        out.collect(cntState.value());
                    }
                })
                .print();

        env.execute();
    }
}
